package com.example.playnote.retrofit

import android.util.Log
import com.example.playnote.BuildConfig
import com.example.playnote.bean.Constant
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitClient {
    companion object {
        fun getInstance() = SingletonHolder.INSTANCE
        private lateinit var retrofit: Retrofit
    }

    /**
     * 双检锁单例模式
     */
    private object SingletonHolder {
        val INSTANCE = RetrofitClient()
    }

    init {
        retrofit = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Constant.BASE_URL)
            .build()
    }

    private fun getOkHttpClient(): OkHttpClient {
        //配置请求的日志打印信息
        val httpLoggingInterceptor =
            HttpLoggingInterceptor { message ->
                if (BuildConfig.DEBUG) {
                    Log.i("--", "RetrofitFactory log: $message")
                }
            }
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return OkHttpClient.Builder()
            .connectTimeout(120, TimeUnit.SECONDS)
            .readTimeout(120, TimeUnit.SECONDS)
            .writeTimeout(120, TimeUnit.SECONDS)
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .addInterceptor(httpLoggingInterceptor)
//            .addInterceptor(Interceptor { chain ->
//                val request = chain.request()
//                chain.proceed(request.newBuilder().build())
//            })
            .build()
    }
    /**
     * 创建一个 Service
     * @param service Class<T> 需要创建的 Service
     * @return T Service实例
     */
    fun <T> create(service: Class<T>): T = retrofit.create(service)

    //这个重载方法可以修改服务器地址
    fun <T> createBaseUrl(service: Class<T>,baseUrl:String): T =Retrofit.Builder()
        .client(getOkHttpClient())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(baseUrl)
        .build()
        .create(service)

}